/* eslint-disable react/no-access-state-in-setstate */
import React, { PureComponent } from 'react';
import XLSX from 'xlsx';
import { Button } from 'antd';
import TableComponent from './TableComponent';

interface IState {
  excelData: {
    header: string[] | undefined;
    results: object[] | undefined;
  };
  // loading: boolean;
}

export default class ExcelUpload extends PureComponent<any, IState> {
  public readonly state: Readonly<IState> = {
    // eslint-disable-next-line react/no-unused-state
    excelData: {
      header: undefined,
      results: undefined,
    },
    // loading: false
  };

  public onSuccess: any;

  public readerData(rawFile: any) {
    return new Promise((resolve: Function) => {
      const reader = new FileReader();
      reader.onload = (e: any) => {
        const data = e.target.result;
        const workbook = XLSX.read(data, { type: 'array' });
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        const header = this.getHeaderRow(worksheet);
        const results = XLSX.utils.sheet_to_json(worksheet);
        this.generateData({ header, results });
        // this.loading = false;
        // this.setState({ loading: false })
        resolve();
      };
      reader.readAsArrayBuffer(rawFile);
    });
  }

  public generateData = ({ header, results }: any) => {
    //  window.console.log((header, results);
    // this.excelData.header = header
    // this.excelData.results = results
    this.setState({
      excelData: {
        ...this.state.excelData,
        header,
        results,
      },
    });
    // this.onSuccess && this.onSuccess(this.excelData) // 应为赋值或函数调用，而不是看到表达式
    // eslint-disable-next-line no-unused-expressions
    this.onSuccess && this.onSuccess(this.state.excelData);
  };

  // eslint-disable-next-line class-methods-use-this
  public getHeaderRow(sheet: any) {
    const headers = [];
    const range = XLSX.utils.decode_range(sheet['!ref']);
    let C;
    const R = range.s.r;
    /* 从第一排开始 */
    // eslint-disable-next-line no-plusplus
    for (C = range.s.c; C <= range.e.c; ++C) {
      /* 在范围内的每一列上执行 */
      const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })];
      /* 在第一行找到单元格 */
      // eslint-disable-next-line prefer-template
      let hdr = 'UNKNOWN ' + C; // <-- 替换为所需的默认值
      if (cell && cell.t) hdr = XLSX.utils.format_cell(cell);
      headers.push(hdr);
    }
    return headers;
  }

  public excelUploadInput!: HTMLInputElement; // !: 这个是添加明确赋值断言

  public beforeUpload: any;

  public upload = (rawFile: string) => {
    // this.excelUploadInput.value = null
    this.excelUploadInput.value = ''; // 修复程序无法选择同一个excel
    if (!this.beforeUpload) {
      this.readerData(rawFile);
      return;
    }
    const before = this.beforeUpload(rawFile);
    if (before) {
      this.readerData(rawFile);
    }
  };

  public handleClick = (e: any) => {
    const { files } = e.target;
    const rawFile = files[0]; // 只使用 files[0]
    if (!rawFile) return;
    this.upload(rawFile);
  };

  public isExcel = (file: any) => /\.(xlsx|xls|csv)$/.test(file.name);

  public handleDrop = (e: any): any => {
    e.stopPropagation();
    e.preventDefault();
    // if (this.state.loading) return;
    const { files } = e.dataTransfer;
    if (files.length !== 1) {
      // 提示 error('只支持上传一个文件！')
      return;
    }
    const rawFile = files[0]; // 只使用 files[0]
    if (!this.isExcel(rawFile)) {
      // 提示 error('仅支持上载.xlsx、.xls、.csv后缀文件')
      // eslint-disable-next-line consistent-return
      return false;
    }
    this.upload(rawFile);
    e.stopPropagation();
    e.preventDefault();
  };

  public handleDragover = (e: any): any => {
    e.stopPropagation();
    e.preventDefault();
    e.dataTransfer.dropEffect = 'copy';
  };

  public handleUpload = () => {
    this.excelUploadInput.click();
  };

  public render() {
    return (
      <div>
        <input
          ref={(node: any) => {
            this.excelUploadInput = node;
          }}
          style={{
            display: 'none',
          }}
          type="file"
          accept=".xlsx, .xls"
          onChange={this.handleClick}
        />
        <div
          className="drop"
          style={{
            border: '2px dashed #bbb',
            width: '600px',
            height: '160px',
            lineHeight: '160px',
            margin: '0 auto',
            fontSize: '24px',
            borderRadius: '5px',
            textAlign: 'center',
            color: '#bbb',
            position: 'relative',
          }}
          onDrop={this.handleDrop}
          onDragEnter={this.handleDragover}
          onDragOver={this.handleDragover}
        >
          这个是可以拖拽的
          <Button style={{ marginLeft: '16px' }} type="primary" onClick={this.handleUpload}>
            上传Excel
          </Button>
        </div>
        {/* header: any results: any */}
        <TableComponent excelData={this.state.excelData} />
      </div>
    );
  }
}
